﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using Core.Utilities;

namespace Core
{
    /// <summary>
    /// String class using for controlling the text value
    /// </summary>
    public class StringUtil
    {
        /// <summary>
        /// This use for checking the email format which is valid or invalid
        /// </summary>
        /// <param name="email"></param>
        /// <returns>Return True if the email is valid, but False if the email is not valid.</returns>
        public static bool IsEmailValid(string email)
        {
            Regex RegexEmail = new Regex("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
            return RegexEmail.IsMatch(email);
        }

        /// <summary>
        /// This use for encoding html tag in text value
        /// </summary>
        /// <param name="value"></param>
        /// <returns>Return string which is encoded already.</returns>
        public static string EncodeHTML(string value)
        {
            return HttpUtility.UrlEncodeUnicode(value);
            //return HttpContext.Current.Server.HtmlEncode(value);
        }

        /// <summary>
        /// Encodes the HTML with out unicode.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static string EncodeHTMLWithOutUnicode(string value)
        {
            return HttpContext.Current.Server.HtmlEncode(value);
        }

        /// <summary>
        /// This use for decoding html tag in text value
        /// </summary>
        /// <param name="value"></param>
        /// <returns>Return string which is encoded already.</returns>
        public static string DecodeHTML(string value)
        {
            return HttpUtility.UrlDecode(value);
            //return HttpContext.Current.Server.HtmlEncode(value);
        }

        /// <summary>
        /// Decodes the HTML with out unicode.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static string DecodeHTMLWithOutUnicode(string value)
        {
            return HttpContext.Current.Server.HtmlEncode(value);
        }

        /// <summary>
        /// This use for getting a original text value. This will cut off the html tag.
        /// </summary>
        /// <param name="value"></param>
        /// <returns>Return string original text</returns>
        public static string HTMLStrip(string value)
        {
            return Regex.Replace(value, @"<(.|\n)*?>", string.Empty);
        }

        /// <summary>
        /// Cuts the string.
        /// </summary>
        /// <param name="str">The STR.</param>
        /// <param name="isStrip">if set to <c>true</c> [is strip].</param>
        /// <param name="isEncode">if set to <c>true</c> [is encode].</param>
        /// <param name="Length">The length.</param>
        /// <param name="isFullWord">if set to <c>true</c> [is full word].</param>
        /// <returns></returns>
        public static string CutString(string str, bool isStrip, bool isEncode, int? Length, bool isFullWord)
        {
            if (isStrip)
            {
                str = HTMLStrip(str);
            }
            if (isEncode)
            {
                str = HttpUtility.HtmlEncode(str);
            }
            if (Length != null)
            {
                if (str.Length > Length.Value)
                {
                    str = str.Substring(0, Length.Value);

                    if (isFullWord)
                    {

                        string[] tmpStr = str.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                        if (tmpStr.Length > 1)
                        {
                            List<string> lsStr = new List<string>();
                            lsStr.AddRange(tmpStr);

                            str = string.Empty;
                            for (int i = 0; i < lsStr.Count - 1; i++)
                            {
                                str += lsStr[i] + ' ';
                            }
                            if (str.Length > 0)
                            {
                                str = str.Substring(0, str.Length - 1);
                            }
                        }
                    }
                }

            }

            return str;
        }

        /// <summary>
        /// Randoms the string.
        /// </summary>
        /// <param name="size">The size.</param>
        /// <param name="lowerCase">if set to <c>true</c> [lower case].</param>
        /// <returns></returns>
        public static string RandomString(int size, bool lowerCase)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            for (int i = 0; i < size; i++)
            {
                char ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }
            if (lowerCase)
                return builder.ToString().ToLower();
            return builder.ToString();
        }

        /// <summary>
        /// Gets the string from object.
        /// </summary>
        /// <param name="obj">The obj.</param>
        /// <returns></returns>
        public static string GetStringFromObject(Object obj)
        {
            string result = obj.ToString().Trim();

            return result;
        }

        /// <summary>
        /// Gets the string from array.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns></returns>
        public static string GetStringFromArray(string[] message)
        {
            string result = "";

            if (message != null)
            {
                for (int i = 0; i < message.Length; i++)
                {
                    string inner = GetInnerMessage(message[i]);
                    result += inner;

                    if (i + 1 < message.Length)
                    {
                        result += ",";
                    }
                }

                if (result.EndsWith(","))
                {
                    result = result.Substring(0, result.Length - 1);
                }
            }

            return result;
        }

        /// <summary>
        /// Gets the string from hashtable.
        /// </summary>
        /// <param name="hash">The hash.</param>
        /// <returns></returns>
        public static string GetStringFromHashtable(Hashtable hash)
        {
            string result = "";

            if (hash != null)
            {
                // Get all the values in the hashtable and sort them
                ArrayList values = ArrayUtil.GetValues(hash);
                values.Sort();

                foreach (object obj in values)
                {
                    foreach (DictionaryEntry dic in hash)
                    {
                        if (dic.Value == obj)
                        {
                            result += dic.Value + ", ";
                            break;
                        }
                    }
                }

                if (result.EndsWith(", "))
                {
                    result = result.Substring(0, result.Length - 2);
                }
            }

            return result;
        }

        /// <summary>
        /// Gets the inner message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns></returns>
        public static string GetInnerMessage(string message)
        {
            //Catch SOAPException from {"System.Web.Services.Protocols.SoapException: Server was unable to process request.
            if (message.Contains("System.Web.Services.Protocols.SoapException"))
            {
                int first = message.IndexOf("--->");
                first += 5;
                int second = message.IndexOf("   at ");

                return message.Substring(first, second - first);
            }
            return message;
        }

        /// <summary>
        /// Strings to byte array.
        /// </summary>
        /// <param name="str">The STR.</param>
        /// <returns></returns>
        public static byte[] StringToByteArray(string str)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            return encoding.GetBytes(str);
        }

        /// <summary>
        /// Bytes the array to string.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public static string ByteArrayToString(byte[] data)
        {
            UTF8Encoding enc = new UTF8Encoding();
            string str = enc.GetString(data);

            return str;
        }
    }
}
